<template>
  <div ref="mainCon">
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form
          :inline="true"
          :model="filterField"
          :rules="rules"
          ref="searchConditions"
        >
          <el-col :lg="8" :xl="6">
            <el-form-item label="时间" class="row-padding-bottom">
              <el-row class="timeBox">
                <el-col :span="11">
                  <el-date-picker
                    v-model="startDate"
                    @change="changeDate"
                    :picker-options="expireTimeOption"
                    :clearable="false"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-col>
                <el-col :span="2"
                  ><span style="margin-left: 3px">至</span></el-col
                >
                <el-col :span="11">
                  <el-date-picker
                    v-model="endDate"
                    @change="changeDate"
                    :picker-options="expireTimeOption"
                    :clearable="false"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="参建单位" class="row-padding-bottom">
              <el-select
                :disabled="isFB"
                v-model="filterField.projectCompanyId"
                clearable
                filterable
                placeholder="请选择"
                @change="changeCompany"
              >
                <el-option
                  v-for="(item, index) of companyList"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="班组" class="row-padding-bottom">
                <el-select
                  v-model="filterField.groupId"
                  clearable
                  filterable
                  placeholder="请先选择参建单位"
                >
                  <el-option
                    v-for="(item, index) of groupIdOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="工人" class="row-padding-bottom name">
                <el-input
                  placeholder="请输入姓名或身份证号"
                  clearable
                  v-model="filterField.keyword"
                  @blur="filterField.keyword = changeValue($event)"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="状态" class="row-padding-bottom">
                <el-select
                  v-model="filterField.inRange"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) of inrangeList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="方向" class="row-padding-bottom">
                <el-select
                  v-model="filterField.direction"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) of directionList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="考勤卡号" class="row-padding-bottom">
                <el-input
                  v-model="filterField.attNo"
                  placeholder="请输入考勤卡号"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :lg="8" :xl="6">
            <el-form-item label="">
              <a
                @click="toggleAdvanced"
                style="margin-left: 40px; color: #409eff; cursor: pointer"
                class="btnColor"
              >
                {{ advanced ? '收起' : '展开' }}
                <i
                  :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                ></i>
              </a>
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchList"
                class="searchBtn"
              >
                <span>搜索</span>
              </el-button>
            </el-form-item>
          </el-col>
          <!-- <el-form-item class="fr setRule">
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont iconshezhi"
              @click="setRule"
              v-if="isSetting || isQy"
            >
              <span class="opetareText">考勤规则设置</span>
            </el-button>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaochu"
              @click="exportExcel"
            >
              <span class="opetareText">导出报表</span>
            </el-button>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaochu"
              @click="exportNoAttExcel"
              v-sdc
            >
              <span class="opetareText">导出无考勤人员</span>
            </el-button>
          </el-form-item> -->
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px">
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont iconshezhi"
            @click="setRule"
            v-if="(isSetting || isQy) && showHistory"
          >
            <span class="opetareText">考勤规则设置</span>
          </el-button>
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icondaochu"
            @click="exportExcel"
          >
            <span class="opetareText">导出报表</span>
          </el-button>
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icondaochu"
            @click="exportNoAttExcel"
            v-sdc
          >
            <span class="opetareText">导出无考勤人员</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          v-loading="loading"
          style="border: 1px solid #dfe6ec"
          @sort-change="sortChange"
        >
          <el-table-column
            prop="employeeName"
            label="姓名"
            align="center"
            :formatter="formatTd"
            min-width="140"
          ></el-table-column>
          <el-table-column
            prop="idcard"
            label="身份证号"
            align="center"
            :formatter="formatTd"
            width="175px"
          >
            <template slot="header">
              <span>身份证号</span>
              <span
                class="icon iconfont iconxianshi"
                @click="changeDeseHandler"
                v-if="!isHiddenIdcard"
              ></span>
              <span
                class="icon iconfont iconyincang"
                @click="changeDeseHandler"
                v-if="isHiddenIdcard"
              ></span>
            </template>
            <template slot-scope="scope">
              <p v-if="!isHiddenIdcard">
                {{ scope.row.idcard | deseHandler(4, 4, '*') || '' }}
              </p>
              <p v-else>{{ scope.row.idcard }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="attNo"
            label="考勤卡号"
            align="center"
            width="175px"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column prop="companyName" label="参建单位" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.companyName"
                :columnName="'companyName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="groupName"
            label="所属班组"
            align="center"
            width="175px"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="punchTime"
            label="打卡时间"
            align="center"
            :formatter="formatTd"
            width="180px"
            sortable="custom"
          ></el-table-column>
          <!-- <el-table-column prop="address" label="打卡地址" align="center" :formatter=formatTd></el-table-column> -->
          <el-table-column prop="address" label="打卡地址" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.address"
                :columnName="'address'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            property="path"
            label="打卡图片"
            :formatter="formatTd"
            min-width="120px"
          >
            <template slot-scope="scope">
              <el-image
                v-if="scope.row.path"
                style="width: 50px; height: 50px"
                :src="scope.row.path"
                :preview-src-list="scope.row.list"
              >
              </el-image>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="temperature"
            label="打卡时体温"
            align="center"
            width="175px"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.temperature">
                <span
                  v-if="scope.row.temperature / 1 < 37.3"
                  class="successColor"
                  >{{ scope.row.temperature }}℃</span
                >
                <span v-else style="color: red"
                  >{{ scope.row.temperature }}℃</span
                >
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="inRange"
            label="状态"
            align="center"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.inRange == 1" class="successColor"
                >范围内</span
              >
              <span v-else class="errorColor">范围外</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="direction"
            label="方向"
            align="center"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.direction == 1">进场</span>
              <span v-else-if="scope.row.direction == 0">出场</span>
              <span v-else>无方向</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="attType"
            label="打卡方式"
            align="center"
            :formatter="formatTd"
            min-width="120px"
          ></el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <!-- getTableList为获取子组件的数据 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'
import { mapState, mapActions } from 'vuex'
export default {
  props: {
    projectId: {
      type: Object,
      default: '',
    },
    isSetting: {
      type: Boolean,
      default: false,
    },
    isFB: {
      type: Boolean,
      default: false,
    },
    showHistory: {
      type: Boolean,
      default: false,
    },
  },
  // props: ["projectId"],
  data() {
    return {
      expireTimeOption: {
        disabledDate(date) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          //不能选择当前日期以后
          return date.getTime() > Date.now()
        },
      },
      hiddleToolBar: false,
      advanced: false,
      tableHeight: null,
      //表格数据
      tableList: [],
      requestUrl: 'api-att/cs/att/expand/attlist',
      // value1:'',
      companyList: [],

      directionList: [
        { name: '进场', id: 1 },
        { name: '出场', id: 0 },
        { name: '无方向', id: -1 },
      ],
      inrangeList: [
        { name: '范围内', id: 1 },
        { name: '范围外', id: 0 },
      ],
      //搜索条件
      filterField: {
        // projectId:"",   //项目id
        year: '', //年
        month: '', //月份
        startDay: '',
        endDay: '',
        uscc: '', //参见单位
        projectCompanyId: '',
        groupId: '', //班组
        keyword: '', //工人姓名
        inRange: '', //状态
        direction: '', //进出方向
      },
      startDate: '',
      endDate: '',
      loading: true, //考勤loading
      //   tableHeight:window.innerHeight - 200,
      orglist: [],
      isShow: false,
      value: '', //下拉数据
      options: [],
      isQy: '',
      clearable: false,
      isHiddenIdcard: false, // 身份证是否显示
      isSearch: true,
    }
  },
  created() {
    const year = new Date().getFullYear()
    this.filterField.year = year
    const month = new Date().getMonth() * 1 + 1
    this.filterField.month = month
    const day = new Date().getDate()
    this.filterField.startDay = this.filterField.endDay = day
    this.startDate = year + '-' + month + '-' + day
    this.endDate = year + '-' + month + '-' + day
    this.$store.commit('SET_INFO', ['groupIdOptions', []])
    //人员档案页面跳转该页面传入人员姓名
    this.filterField.keyword = this.$route.query.employeeName
      ? this.$route.query.employeeName
      : ''

    this.filterField.projectId = this.projectId
    if (
      this.$store.state.userType == 'PROJECT_ADMINISTRATOR' ||
      this.$store.state.userType == 'LABOR_ADMINISTRATOR'
    ) {
      this.isQy = true
    } else {
      this.isQy = false
    }
    if (!this.isFB) {
      this.$nextTick(function () {
        this.$refs.pagination.getTableListData()
      })
    }

    this.getCompanyList()
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  computed: {
    ...mapState(['groupIdOptions']),
  },
  methods: {
    changeDate(val) {
      this.isSearch = true
      /* const year = new Date().getFullYear()*1
        const month = new Date().getMonth()*1+1
        if(val&&(val.split('-')[1]*1!=month||val.split('-')[0]*1!=year)){
            this.$message.error('仅支持查询当前月份');
            this.isSearch = false
            return
        } */
      if (this.startDate && this.endDate && this.startDate > this.endDate) {
        this.$message.error('开始日期不能大于结束日期')
        this.isSearch = false
        return
      }
      const startMonth = this.startDate && this.startDate.split('-')[1] * 1
      const startYear = this.startDate && this.startDate.split('-')[0] * 1
      const endMonth = this.endDate && this.endDate.split('-')[1] * 1
      const endYear = this.endDate && this.endDate.split('-')[0] * 1
      if (startMonth !== endMonth || startYear !== endYear) {
        this.$message.error('仅支持查询同月日期')
        this.isSearch = false
        return
      } else {
        this.filterField.year = startYear + ''
        this.filterField.month = startMonth + ''
        this.filterField.startDay =
          this.startDate && this.startDate.split('-')[2]
        this.filterField.endDay = this.endDate && this.endDate.split('-')[2]
      }
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    ...mapActions(['getGroupList']),
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 242

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      var list = []
      this.drawerLoading = false
      for (var i = 0; i < this.tableList.length; i++) {
        list.push(this.tableList[i].path)
      }

      for (var i = 0; i < this.tableList.length; i++) {
        var container = list

        var frontArr = container.slice(0, i)
        var behindArr = container.slice(i, this.tableList.length)
        var imgList = behindArr.concat(frontArr)
        this.tableList[i].list = imgList
      }

      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      if (this.isSearch) {
        /* this.filterField.year = "";
        this.filterField.month = "";
        this.filterField.startDay = "";
        this.filterField.endDay = "";
        if (this.startDate) {
            this.filterField.year = this.startDate.split("-")[0];
            this.filterField.month = this.startDate.split("-")[1];
            this.filterField.startDay = this.startDate.split("-")[2];
        } 
        if (this.endDate) {
            this.filterField.year = this.endDate.split("-")[0];
            this.filterField.month = this.endDate.split("-")[1];
            this.filterField.endDay = this.endDate.split("-")[2];
        } 
        if (!this.startDate&&!this.endDate) {
            this.filterField.year = "";
            this.filterField.month = "";
            this.filterField.startDay = "";
            this.filterField.endDay = "";
        } */
        this.$refs.pagination.getTableListData()
      } else {
        this.$message.error('请按规则选择日期')
      }
    },
    exportExcel() {
      if (this.tableList.length > 0) {
        window.location.href =
          common.commonApi +
          'api-att/cs/att/expand/exportatt?projectId=' +
          this.filterField.projectId +
          '&year=' +
          this.filterField.year +
          '&month=' +
          this.filterField.month +
          '&startDay=' +
          this.filterField.startDay +
          '&endDay=' +
          this.filterField.endDay +
          '&uscc=' +
          this.filterField.uscc +
          '&groupId=' +
          this.filterField.groupId +
          '&keyword=' +
          this.filterField.keyword +
          '&sortField=' +
          this.filterField.sortField +
          '&sort=' +
          this.filterField.sort +
          '&access_token=' +
          localStorage.getItem('access_token') +
          '&inRange=' +
          this.filterField.inRange +
          '&direction=' +
          this.filterField.direction
      } else {
        this.$message({
          type: 'warning',
          message: '无数据导出',
        })
      }
    },
    //导出无考勤人员
    exportNoAttExcel() {
      window.location.href =
        common.commonApi +
        'api-att/cs/att/expand/exportNoAtt?projectId=' +
        this.filterField.projectId +
        '&startDate=' +
        this.startDate +
        '&endDate=' +
        this.endDate +
        '&access_token=' +
        localStorage.getItem('access_token')
    },
    getCompanyList() {
      this.axios({
        method: 'post',
        // url: "api-p/projectcompany/expand/findbyprojectid",
        url: 'api-p/projectcompany/expand/findprojectcompany',
        data: {
          projectId: this.projectId,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.companyList = response.data.result
              if (this.isFB) {
                this.filterField.uscc = response.data.result[0].uscc
                this.filterField.projectCompanyId = response.data.result[0].code
                this.getGroupList({
                  projectId: this.projectId,
                  uscc: this.filterField.uscc,
                  projectCompanyId: this.filterField.projectCompanyId,
                })
                this.$refs.pagination.getTableListData()
              }
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    changeCompany() {
      this.$store.commit('SET_INFO', ['groupIdOptions', []])
      this.filterField.groupId = ''
      var projectCompanyId = this.filterField.projectCompanyId
      if (projectCompanyId) {
        const findOne = this.companyList.find(
          (v) => v.code === projectCompanyId
        )
        this.filterField.uscc = findOne.uscc
        this.getGroupList({
          projectId: this.projectId,
          uscc: this.filterField.uscc,
          projectCompanyId,
        })
      } else {
        this.filterField.uscc = ''
      }
    },
    setRule() {
      this.$router.push({
        path: '/home/constructAttendance/constructPunchCardRuleList',
        name: 'constructPunchCardRuleList',
        query: {
          projectId: this.projectId,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/constructAttendance/qyConstructAttendanceContainer',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    changeDeseHandler() {
      this.isHiddenIdcard = !this.isHiddenIdcard
    },
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
}
</script>

<style scoped lang="less">
@import '../../../static/css/filterArea.less';
.commomPadding {
  padding-top: 0;
  /deep/ .imgPrev {
    width: 50px;
  }
}
.timeBox {
  /deep/ .el-input__inner,
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner,
  .searchInputWidth .el-input--suffix .el-input__inner {
    width: 105px !important;
  }
  /deep/ .el-input--prefix .el-input__inner {
    padding: 0 0 0 10px;
  }
  /deep/.el-icon-date:before {
    content: '';
  }
  /deep/ .el-icon-circle-close {
    color: #666;
    padding: 0px;
    text-align: right;
  }
}
// tab样式位置
#app /deep/ .root /deep/ .operateList {
  position: fixed;
  top: 214px;
}

.setRule {
  position: absolute;
  top: -60px;
  right: 0;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 230px;
}

@media all and (min-width: 1360px) and (max-width: 1470px) {
  .el-form--inline .el-form-item {
    margin-right: 0;
  }
}
@media screen and (min-width: 1280px) and (max-width: 1366px) {
  .searchInputWidth /deep/.el-form-item__label {
    width: 70px;
  }
}

.iconxianshi,
.iconyincang {
  cursor: pointer;
}
</style>
